package common;

import java.util.Calendar;

/**
 * A source of the current time, used for dependency injection in our test cases.
 * Normally, this behaves identical as Calendar.getInstance() but has an option to set the time
 * to some different time and have that be returned.  This allows test cases to "change" the
 * system time in their test cases.
 * @author Royce
 *
 */
public class TimeSource {
	
	private static Calendar curTime;
	private static TimeSource _instance = null;
	
	private TimeSource() {
		curTime = null;
	}
	
	/**
	 * 
	 * @return the one and only instance of this TimeSource
	 */
	public static TimeSource instance() {
		if (_instance == null) _instance = new TimeSource();
		
		return _instance;
	}
	
	/**
	 * 
	 * @return true if a time is set for this TimeSource
	 */
	public boolean isSet() {
		return (curTime != null);
	}
	
	/**
	 * Resets the current time, so that any further queries of the time will return
	 * Calendar.getInstance() until a new time is set.
	 */
	public void reset() {
		curTime = null;
	}
	
	/**
	 * Sets the time of this TimeSource
	 * @param time The time, represented by a Calendar object, that this TimeSource should return
	 * until reset or set to a different time.
	 */
	public void setTime(Calendar time) {
		curTime = time;
	}
	
	/**
	 * 
	 * @return the set time if it is set, or Calendar.getInstance() if it is not.
	 */
	public Calendar getTime() {
		if (!isSet()) {
			return Calendar.getInstance();
		}
		else {
			return (Calendar)curTime.clone();
		}
	}

}
